package services

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"go_motor_catalog/dao"
	"go_motor_catalog/util"
	"strings"
)

const typeUrl = "https://api.triumphtechnicalinformation.com/handbooks/products/product-ranges"

const modelUrl = "https://api.triumphtechnicalinformation.com/handbooks/products/model-names?productRange="

const yearUrl = "https://api.triumphtechnicalinformation.com/handbooks/products/model-years?modelName="

const catalogUrl = "https://api.triumphtechnicalinformation.com/handbooks/product-details/"

const documentUrl = "https://api.triumphtechnicalinformation.com/handbooks/documents?modelCode=MODELCODE&modelYear=MODELYEAR&state=STATE&onlyValid=true&market="

const fileBaseUrl = "https://api.triumphtechnicalinformation.com/handbooks/documents/"

type Triumph struct {
}

type TriumphRes struct {
	ModelName string
	ModelYear string
	Catalog   string
}

func NewTriumphOm() *Triumph {
	return &Triumph{}
}

func (t *Triumph) getTypes() []map[string]interface{} {
	body := util.NewHttpUtil().Get(typeUrl)
	var types []map[string]interface{}
	err := json.Unmarshal([]byte(body), &types)
	if err != nil {
		fmt.Println("获取凯旋类型错误", err)
		return nil
	}
	return types
}

func (t *Triumph) getModels(param string) []string {
	var res []string
	body := util.NewHttpUtil().Get(modelUrl + param)
	var jsonBody []string
	err := json.Unmarshal([]byte(body), &jsonBody)
	if err != nil {
		fmt.Println("获取凯旋models错误", err)
		return nil
	}
	res = append(res, jsonBody...)
	return res
}

func (t *Triumph) getYears(model string) []map[string]interface{} {
	model = strings.ReplaceAll(model, " ", "%20")
	body := util.NewHttpUtil().Get(yearUrl + model)
	var jsonBody []map[string]interface{}
	err := json.Unmarshal([]byte(body), &jsonBody)
	if err != nil {
		fmt.Println("获取凯旋产品年份错误", err)
		return nil
	}
	return jsonBody
}

func (t *Triumph) getCatalogs(id string) map[string]interface{} {
	body := util.NewHttpUtil().Get(catalogUrl + id)
	var jsonBody map[string]interface{}
	err := json.Unmarshal([]byte(body), &jsonBody)
	if err != nil {
		fmt.Println("获取凯旋图纸", err)
		return nil
	}
	return jsonBody
}

func (t *Triumph) getDocuments(modelCode string, modelYear string, state string) []map[string]interface{} {
	url := documentUrl
	url = strings.ReplaceAll(url, "MODELCODE", modelCode)
	url = strings.ReplaceAll(url, "MODELYEAR", modelYear)
	url = strings.ReplaceAll(url, "STATE", state)
	body := util.NewHttpUtil().Get(url)
	var jsonBody []map[string]interface{}
	err := json.Unmarshal([]byte(body), &jsonBody)
	if err != nil {
		fmt.Println("获取凯旋详细图纸", err)
		return nil
	}
	return jsonBody
}

func (t *Triumph) getDocumentUrls() []*TriumphRes {
	var res []*TriumphRes
	types := t.getTypes()
	//获取所有类型
	for i := range types {
		typeId := fmt.Sprintf("%v", types[i]["id"])
		//获取所有model
		models := t.getModels(typeId)
		for m := range models {
			//model名称
			modelName := models[m]
			//获取所有year
			years := t.getYears(modelName)
			for y := range years {
				yearId := fmt.Sprintf("%v", years[y]["_id"])
				//model year
				yearName := fmt.Sprintf("%v", years[y]["modelYear"])
				//获取所有catalog
				catalogs := t.getCatalogs(yearId)
				modelCode := fmt.Sprintf("%v", catalogs["modelCode"])
				state := fmt.Sprintf("%v", catalogs["state"])
				modelYear := fmt.Sprintf("%v", catalogs["modelYear"])
				//获取所有document
				documents := t.getDocuments(modelCode, modelYear, state)
				for d := range documents {
					language := fmt.Sprintf("%v", documents[d]["language"])
					id := fmt.Sprintf("%v", documents[d]["_id"])
					format := fmt.Sprintf("%v", documents[d]["format"])
					if language == "zh-CN" {
						fileType := strings.Split(format, "/")[1]
						documentUrl := fileBaseUrl + id + "/" + fileType
						resModel := &TriumphRes{
							ModelName: modelName,
							ModelYear: yearName,
							Catalog:   documentUrl,
						}
						res = append(res, resModel)
						break
					} else if d == (len(documents) - 1) {
						id = fmt.Sprintf("%v", documents[0]["_id"])
						format = fmt.Sprintf("%v", documents[0]["format"])
						fileType := strings.Split(format, "/")[1]
						documentUrl := fileBaseUrl + id + "/" + fileType
						fmt.Println(documentUrl)
						resModel := &TriumphRes{
							ModelName: modelName,
							ModelYear: yearName,
							Catalog:   documentUrl,
						}
						res = append(res, resModel)
						break
					}
				}
			}
		}
	}
	return res
}

func (t *Triumph) CrawTriumphOm(db *gorm.DB) {
	urls := t.getDocumentUrls()
	if len(urls) > 0 {
		modelOmDao := dao.NewManualModelOmDao(db)
		catalogOmDao := dao.NewManualCatalogOmDao(db)
		for i := range urls {
			param := urls[i]
			modelParam := &dao.ManualModelOm{
				ModelName: param.ModelName,
				ModelYear: param.ModelYear,
				BrandId:   6,
			}
			catalogParam := &dao.ManualCatalogOm{
				CatalogUrl:  param.Catalog,
				CatalogDesc: "",
			}
			modelId := modelOmDao.CreateManualModelOm(modelParam)
			catalogParam.ModelId = modelId
			catalogOmDao.CreateManualCatalogOm(catalogParam)
			fmt.Println(param.ModelName, "-", param.ModelYear, "-successfull")
		}
		fmt.Print("all successfull")
	}
}
